//
//  CheckVersion.m
//  yeeyan
//
//  Created by liunian on 13-7-26.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "CheckVersion.h"
#import "NSString+SBJSON.h"


#define iApp_url @"http://itunes.apple.com/lookup?id=693893823"
@interface CheckVersion ()
@property (nonatomic, copy) NSString    *trackViewURL;
@end
@implementation CheckVersion
- (void)dealloc{
}

+(CheckVersion *)sharedCVInstance{
    static CheckVersion *_sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedManager = [[CheckVersion alloc] init];
    });
    
    return _sharedManager;
}

- (void)checkVersionOfServerWithDelegate:(id<VersionDelegate>)delegate{
    if ([Util unfoldUpdateTime] && delegate == nil) {
        return;
    }
    
    NSString *URL = iApp_url;
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:URL]];
    [request setHTTPMethod:@"POST"];
    NSHTTPURLResponse *urlResponse = nil;
    NSError *error = nil;
    NSData *recervedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
    
    NSString *results = [[NSString alloc] initWithBytes:[recervedData bytes] length:[recervedData length] encoding:NSUTF8StringEncoding];
    NSDictionary *dic = [results JSONValue];
    NSArray *infoArray = [dic objectForKey:@"results"];
    if ([infoArray count]) {
        NSDictionary *releaseInfo = [infoArray objectAtIndex:0];
        NSString *lastVersion = [releaseInfo objectForKey:@"version"];
        
        NSString *releaseNotes = [releaseInfo objectForKey:@"releaseNotes"];
        NSString *message = [NSString stringWithFormat:@"%@\n\n%@",releaseNotes,@"有新版本更新啦！"];
        
        if (![lastVersion isEqualToString:APP_VERSION]) {

            self.trackViewURL = [releaseInfo objectForKey:@"trackViewUrl"];
            NSString *title = [NSString stringWithFormat:@"检测到新版本%@",lastVersion];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"立即更新", nil];
                [alert show];
                
                if ([delegate respondsToSelector:@selector(hasNewVersion)]) {
                    [delegate hasNewVersion];
                }
            });
            
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([delegate respondsToSelector:@selector(noNewVersion)]) {
                    [delegate noNewVersion];
                }
            });
        }
    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([delegate respondsToSelector:@selector(noNewVersion)]) {
                [delegate noNewVersion];
            }
        });
    }
}

#pragma mark UIAlertViewDelegate
-(void)willPresentAlertView:(UIAlertView *)alertView{
    int i = 0;
    for( UIView * view in alertView.subviews ){
        if( [view isKindOfClass:[UILabel class]]){
            UILabel* label = (UILabel*) view;
            if (i) {
                label.textAlignment = [Util getAlign:ALIGNTYPE_LEFT];
            }else{
                i++;
            }
        }
    }
}
- (void)alertViewCancel:(UIAlertView *)alertView{
    
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.numberOfButtons == 2) {
        if (buttonIndex == 0) {
            return;
        }
        NSURL *url = [NSURL URLWithString:self.trackViewURL];
        [[UIApplication sharedApplication] openURL:url];
    }else{
        NSURL *url = [NSURL URLWithString:self.trackViewURL];
        [[UIApplication sharedApplication] openURL:url];
    }
    
}

@end
